/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.facilscrum.form.departamentos;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import javax.swing.table.DefaultTableModel;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;
import org.javscaz.javscaztools.utilidades.Utilidades;
import org.facilscrum.beans.Departamento;
import org.facilscrum.beans.Gruposusuarios;
import org.facilscrum.controller.DepartamentoController;
import org.facilscrum.generales.Mensajeria;

/**
 *
 * @author avbravo
 */
public class DepartamentoForm extends javax.swing.JInternalFrame {

    DefaultTableModel modelo;
    DepartamentoController departamentoController = new DepartamentoController();
    Departamento departamento = new Departamento();

    /**
     * Creates new form DepartamentoForm
     */
    public DepartamentoForm() {
        initComponents();
        modelo = (DefaultTableModel) jTable1.getModel();
        cargarTabla();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButtonAgregar = new javax.swing.JButton();
        jButtonModificar = new javax.swing.JButton();
        jButtonEliminar = new javax.swing.JButton();
        jButtonConsultar = new javax.swing.JButton();
        jButtonCerrar = new javax.swing.JButton();
        jTextFieldIdDepartamento = new javax.swing.JTextField();
        jTextFieldDepartamento = new javax.swing.JTextField();
        jButtonLimpiar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldEdificio = new javax.swing.JTextField();
        jButtonImprimirTodos = new javax.swing.JButton();

        setClosable(true);
        setTitle("Departamentos");

        jLabel1.setText("Codigo");

        jLabel2.setText("Nombre");

        jButtonAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/avbravo/jscrum/gif/save_icon.gif"))); // NOI18N
        jButtonAgregar.setToolTipText("Agregar");
        jButtonAgregar.setEnabled(false);
        jButtonAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAgregarActionPerformed(evt);
            }
        });

        jButtonModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/avbravo/jscrum/gif/edit.png"))); // NOI18N
        jButtonModificar.setToolTipText("Modificar");
        jButtonModificar.setEnabled(false);
        jButtonModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonModificarActionPerformed(evt);
            }
        });

        jButtonEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/avbravo/jscrum/gif/delete.gif"))); // NOI18N
        jButtonEliminar.setToolTipText("Eliminar");
        jButtonEliminar.setEnabled(false);
        jButtonEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEliminarActionPerformed(evt);
            }
        });

        jButtonConsultar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/avbravo/jscrum/gif/search.png"))); // NOI18N
        jButtonConsultar.setToolTipText("Consultar");
        jButtonConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonConsultarActionPerformed(evt);
            }
        });

        jButtonCerrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/avbravo/jscrum/gif/return.gif"))); // NOI18N
        jButtonCerrar.setToolTipText("Cerrar");
        jButtonCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCerrarActionPerformed(evt);
            }
        });

        jTextFieldIdDepartamento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldIdDepartamentoActionPerformed(evt);
            }
        });

        jButtonLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/avbravo/jscrum/gif/clear.png"))); // NOI18N
        jButtonLimpiar.setToolTipText("Limpiar");
        jButtonLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonLimpiarActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Departamento", "Edificio"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLabel3.setText("Edificio");

        jButtonImprimirTodos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/facilscrum/gif/x16/print.png"))); // NOI18N
        jButtonImprimirTodos.setToolTipText("Imprimir todos");
        jButtonImprimirTodos.setEnabled(false);
        jButtonImprimirTodos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonImprimirTodosActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18)
                                .addComponent(jTextFieldIdDepartamento, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonConsultar))
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(jLabel3)
                                    .addGap(18, 18, 18)
                                    .addComponent(jTextFieldEdificio, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                    .addComponent(jLabel2)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jTextFieldDepartamento, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(46, 46, 46)
                        .addComponent(jButtonAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonImprimirTodos)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonCerrar, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 544, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jButtonConsultar)
                    .addComponent(jTextFieldIdDepartamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldDepartamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextFieldEdificio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButtonAgregar)
                        .addComponent(jButtonModificar)
                        .addComponent(jButtonLimpiar)
                        .addComponent(jButtonEliminar)
                        .addComponent(jButtonCerrar))
                    .addComponent(jButtonImprimirTodos))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31))
        );

        jTabbedPane1.addTab("Departamentos", jPanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonModificarActionPerformed
        try {
            if (!guiToData()) {
                return;
            }
            if (departamentoController.update(departamento)) {
                Mensajeria.Mensaje("Se actualizo  exitosamente");
                habilitarEncontrado(true);
                cargarTabla();
            
            } else {
                Mensajeria.MensajeWarning("No se pudo actualizar " + departamentoController.getMensaje());
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "modificar()");
        }

    }//GEN-LAST:event_jButtonModificarActionPerformed

    private void jButtonCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCerrarActionPerformed
        dispose();
    }//GEN-LAST:event_jButtonCerrarActionPerformed

    private void jButtonAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAgregarActionPerformed
        try {
            if (!guiToData()) {
                return;
            }
            if (departamentoController.insert(departamento)) {
                Mensajeria.Mensaje("Se guardo exitosamente");
                habilitarEncontrado(true);
                cargarTabla();
            } else {
                Mensajeria.MensajeWarning("No se pudo guardar " + departamentoController.getMensaje());
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "agregar()");
        }
    }//GEN-LAST:event_jButtonAgregarActionPerformed

    private void jButtonEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEliminarActionPerformed
        try {
            guiToData();
            if(Mensajeria.PreguntaSiNo("Desea eliminar el departamento", "Eliminar").equals("no")){
                Mensajeria.Mensaje("No se elimino el departamento");
                return;
            }
            if (departamentoController.delete(departamento)) {
                Mensajeria.Mensaje("Se elimino exitosamente");
                limpiar();
                habilitarEncontrado(false);
                   cargarTabla();
            } else {
                Mensajeria.MensajeWarning("No se pudo eliminar " + departamentoController.getMensaje());
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "eliminar()");
        }
    }//GEN-LAST:event_jButtonEliminarActionPerformed

    private void jTextFieldIdDepartamentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldIdDepartamentoActionPerformed
        consultar();
    }//GEN-LAST:event_jTextFieldIdDepartamentoActionPerformed

    private void jButtonConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonConsultarActionPerformed
        consultar();
    }//GEN-LAST:event_jButtonConsultarActionPerformed

    private void jButtonLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLimpiarActionPerformed
        limpiar();
        habilitarEncontrado(false);
    }//GEN-LAST:event_jButtonLimpiarActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        try {
            Integer fila = jTable1.getSelectedRow();
            if (fila == -1) {
                Mensajeria.Mensaje("No se selecciono ninguna fila");

                return;
            }

            jTextFieldIdDepartamento.setText(jTable1.getValueAt(fila, 0).toString());
            jTextFieldDepartamento.setText(jTable1.getValueAt(fila, 1).toString());
                        jTextFieldEdificio.setText(jTable1.getValueAt(fila, 2).toString());
            habilitarEncontrado(true);
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "MouseClicked()");
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void jButtonImprimirTodosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonImprimirTodosActionPerformed
        HashMap map = new HashMap();

        try {
            imprimirTodos(departamentoController.getDepartamentolist(), map);
        } catch (JRException ex) {
            Mensajeria.MensajeError(ex, "imprimirtodos()");
        }
    }//GEN-LAST:event_jButtonImprimirTodosActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAgregar;
    private javax.swing.JButton jButtonCerrar;
    private javax.swing.JButton jButtonConsultar;
    private javax.swing.JButton jButtonEliminar;
    private javax.swing.JButton jButtonImprimirTodos;
    private javax.swing.JButton jButtonLimpiar;
    private javax.swing.JButton jButtonModificar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextFieldDepartamento;
    private javax.swing.JTextField jTextFieldEdificio;
    private javax.swing.JTextField jTextFieldIdDepartamento;
    // End of variables declaration//GEN-END:variables

    private void imprimirTodos(List<Departamento> aux, HashMap map) throws JRException {
        try {
            JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(aux);
//Indicamos la ruta del reporte
            InputStream reporte = (InputStream) getClass().getResourceAsStream("/org/facilscrum/reportes/departamento.jasper");
            if (reporte == null) {
                Mensajeria.Mensaje("No se pudo cargar el reporte");
            } else {
                JasperPrint print = JasperFillManager.fillReport(reporte, map, ds);
                JasperViewer.viewReport(print, false);
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "Imprimir()");
        }
    }
    private Boolean consultar() {
        try {
            if (jTextFieldIdDepartamento.getText() == null || jTextFieldIdDepartamento.getText().equals("")) {
                Mensajeria.MensajeWarning("Debe ingresar el id departamento");
                jTextFieldIdDepartamento.requestFocus();
                return false;
            }
            departamento.setIddepartamento(jTextFieldIdDepartamento.getText());
            Departamento d = departamentoController.findByPrimaryKey(departamento);
            if (d != null) {
                departamento = d;
                jTextFieldDepartamento.setText(departamento.getDepartamento());
                jTextFieldEdificio.setText(departamento.getEdificio());
                habilitarEncontrado(true);
            } else {
                Mensajeria.MensajeWarning("No existe registro con ese codigo");
                habilitarEncontrado(false);
            }
            return true;
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "consultar()");
        }
        return false;
    }

    private Boolean guiToData() {
        try {
            if (jTextFieldIdDepartamento.getText() == null || jTextFieldIdDepartamento.getText().equals("")) {
                Mensajeria.MensajeWarning("Debe ingresar el id departamento");
                jTextFieldIdDepartamento.requestFocus();
                return false;
            }

            if (jTextFieldDepartamento.getText() == null || jTextFieldDepartamento.getText().equals("")) {
                Mensajeria.MensajeWarning("Debe ingresar el  departamento");
                jTextFieldDepartamento.requestFocus();
                return false;
            }
              if (jTextFieldEdificio.getText() == null || jTextFieldEdificio.getText().equals("")) {
                Mensajeria.MensajeWarning("Debe ingresar el  edificio");
                jTextFieldEdificio.requestFocus();
                return false;
            }
            departamento.setIddepartamento(jTextFieldIdDepartamento.getText());
            departamento.setDepartamento(jTextFieldDepartamento.getText());
            departamento.setEdificio(jTextFieldEdificio.getText());
            return true;
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "guiToData()");
        }
        return false;
    }
    /*
     * true = habilita modificar, eliminar
     * false = habilita agregar
     */

    private void habilitarEncontrado(Boolean encontrado) {
        jButtonAgregar.setEnabled(!encontrado);
        jButtonModificar.setEnabled(encontrado);
        jButtonEliminar.setEnabled(encontrado);
 jButtonImprimirTodos.setEnabled(encontrado);
    }

    private void limpiar() {
        jTextFieldIdDepartamento.setText("");
        jTextFieldDepartamento.setText("");
        jTextFieldEdificio.setText("");

    }

    private void cargarTabla() {
        try {
             modelo = Utilidades.limpiarModelo(modelo);
            if (departamentoController.selectAll()) {
                for (Departamento d : departamentoController.getDepartamentolist()) {
                    Object[] filas = new Object[3]; // Hay tres columnas en la tabla       
                    filas[0] = d.getIddepartamento();
                    filas[1] = d.getDepartamento();
                      filas[2] = d.getEdificio();
                    modelo.addRow(filas);
                }
                 jButtonImprimirTodos.setEnabled(true);
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "cargarTabla()");
        }
    }
}
